import { connect, history } from 'umi';
import { Spin, message } from 'antd';
import { useEffect, useState } from 'react';
import '../common/style.less';
import { getExpertsSerivice, syncPDFtoOAServices } from '../services/DetailOAService';
import { ChangeControllerContext } from '../common/useOAContext';
import { DetailInfoTopViewOA } from './DetailInfoTopViewOA';
import { DetailInfoCenterViewOA } from './DetailInfoCenterViewOA';
import { DetailInfoBottomViewOA } from './DetailInfoBottomViewOA';
import { getInvoiceCode, getPersonalInfo, getPosIDs, getTenantID, getUserID, renderWaterMarkDom } from '@/utils';
import { RevokeModal } from '../../../Acomponents/RevokeModal';
import { ILoadMapTypeAll } from '@/common';
import { SHTG_CHECKSTATE, SHZ_CHECKSTATE, setOAMessageSev } from '../../../Acommon';
import { approvedAssetAllotSerivice, dealNumAssetAllotSerivice } from '../services';

const DetailInfoViewOA: React.FC<Record<string, any>> = ({ locationProps, curRes }) => {
  /** 样式根名称 */
  const prefix = 'experts-manage-oa-';

  /** 保存详情 */
  const [infoObj, setInfoObj] = useState<Record<string, any>>({});

  const [invalidState, setInvalidState] = useState<Record<string, any>>({}); /**撤销弹窗*/
  // 资产调拨  ---- 锁定物料数量
  const { dealNumAssetAllotRun, dealNumAssetAllotLoading } = dealNumAssetAllotSerivice((res) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
    }
  });

  /** 消息已读已办接口 */
  const { setOAMessageRun, setOAMessageLoaidng } = setOAMessageSev(() => {});
  /** 资产调拨审批同意判断是否可以调用同步接口 */
  const [auditSuccessState, setAuditSuccessState] = useState(false);

  /** 获取详情 */
  const { getExpertsRun, getExpertsLoading, getExpertsReload } = getExpertsSerivice((res) => {
    if (res?.msgFlag) {
      setInfoObj(res?.obj);

      /** 是否是审核中 */
      if (
        res?.obj?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1000` &&
        res?.obj?.state === `${getTenantID()}${ILoadMapTypeAll.STORAGE_TRANSFER_STATUS}1001`
      ) {
        setAuditSuccessState(true);
      }
      // 做已读办理的接口处理
      let infoObject = res?.obj;
      if (infoObject && infoObject?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1015`]) {
        let workFlowNode = infoObject?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1015`];
        if (
          workFlowNode &&
          workFlowNode?.mactivitiTaskList?.length > 0 &&
          workFlowNode?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
          workFlowNode?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
        ) {
          setOAMessageRun({
            // 已读未办
            id: locationProps?.state?.taskId,
            isRemark: 0,
            viewType: 1,
          });
        }
      }
    }
  });

  /** 审核中，审核通过/作废 开关 */
  const [isSHTGFlag, setIsSHTGFlag] = useState(false);
  /** 资产调拨-最后一个人审核通过后调用的同步接口 */
  const { approvedAssetAllotUseRun, approvedAssetAllotUseLoading } = approvedAssetAllotSerivice((res) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
    } else {
      message.error(res?.msg);
    }
  });

  /** 同步审核记录给档案 */
  const { syncPDFtoOARun, syncPDFtoOALoading } = syncPDFtoOAServices((res) => {});
  const syncPDFtoOARunfun = (infoObj) => {
    //需要调用同步接口
    let mactivitiHisTaskInstList =
      infoObj?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1015`]?.mactivitiHisProcinstList?.[0]?.mactivitiHisTaskInstList;
    let resObj = { ...infoObj, paramObject: { mactivitiHisTaskInstList } };
    syncPDFtoOARun(resObj);
  };

  /** 监听数据状态改变，更改状态 */
  useEffect(() => {
    if (infoObj?.state && infoObj?.state == `${getTenantID()}${ILoadMapTypeAll.STORAGE_TRANSFER_STATUS}1001` && infoObj?.checkState == SHZ_CHECKSTATE()) {
      setIsSHTGFlag(true);
    }
    if (isSHTGFlag && infoObj?.checkState == SHTG_CHECKSTATE()) {
      syncPDFtoOARunfun(infoObj);
    }
  }, [infoObj?.state, infoObj?.checkState]);

  /** 撤销回调函数 */
  const revokeReloadCallback = async () => {
    await dealNumAssetAllotRun({ ...infoObj, dealType: 'back' });
  };

  /** 初始化 */
  useEffect(() => {
    if (locationProps?.state?.id) {
      getExpertsRun(locationProps?.state?.id);
    }
  }, [locationProps?.state?.id]);

  // 初始化水印
  // useEffect(() => {
  //   renderWaterMarkDom('bidEvalOAPage-divBox', true);
  //   return () => {
  //     renderWaterMarkDom('bidEvalOAPage-divBox', false);
  //   };
  // }, []);

  /** 监听审核状态 */
  useEffect(() => {
    if (
      auditSuccessState &&
      infoObj?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002` &&
      infoObj?.state === `${getTenantID()}${ILoadMapTypeAll.STORAGE_TRANSFER_STATUS}1003`
    ) {
      approvedAssetAllotUseRun({ ...infoObj, workflowResult: true });
    }
  }, [infoObj?.checkState, infoObj?.state, auditSuccessState]);

  return (
    <ChangeControllerContext.Provider
      value={{
        styleFixCls: prefix,
        infoObj,
        reloadDetail: getExpertsReload,
        invalidState,
        setInvalidState,
        curRes,
        setOAMessageRun,
        taskId: locationProps?.state?.taskId,
      }}
    >
      <Spin spinning={getExpertsLoading || setOAMessageLoaidng || syncPDFtoOALoading}>
        <div className={`${prefix}infoViewOA`} id={'bidEvalOAPage-divBox'}>
          <DetailInfoTopViewOA locationProps={locationProps} />
          <DetailInfoCenterViewOA />
          <DetailInfoBottomViewOA locationProps={locationProps} />
        </div>
      </Spin>
      {/* 撤销弹窗 */}
      {invalidState?.isShow && (
        <RevokeModal
          resObj={invalidState?.resObj}
          revokeRequestUrl={'/assetApplyTransfer/revoke'}
          onClose={() => setInvalidState({})}
          reqBody={{ id: invalidState?.resObj?.id, state: `${getTenantID()}${ILoadMapTypeAll?.STORAGE_TRANSFER_STATUS}1000` }}
          modalTip={
            <div style={{ color: '#000' }}>
              确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.applyTitle}</span>】的审核, 撤销后可重新提交！
            </div>
          }
          reloadRequest={() => {
            revokeReloadCallback()
            history.push({
              pathname: locationProps?.state?.returnPathName,
              state: {
                delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
                returnPathName: locationProps?.state?.returnPathName,
              },
            });
          }}
        />
      )}
    </ChangeControllerContext.Provider>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(DetailInfoViewOA);
